<?php

namespace app\admin\controller\depot;

// 引入基类控制器
use app\common\controller\Backend;

use think\exception\PDOException;
use Exception;
use think\Db;

// 供应商
class Back extends Backend
{
  protected $BackProductModel;
  protected $OrderModel;
  protected $OrderProductModel;
  protected $AddressModel;

  public function __construct()
  {
    parent::__construct();

    $this->model = model('Depot.Back.Back');
    $this->BackProductModel = model('Depot.Back.Product');
    $this->OrderModel = model('Order.Order');
    $this->OrderProductModel = model('Order.Product');
    $this->AddressModel = model('Business.Address');

    // 注入前置数据
    $this->view->assign("statusList", $this->model->getStatusList());
    $this->view->assign("statusList", $this->model->getStatusList());
  }

  public function index()
  {

    $this->request->filter(['strip_tags', 'trim']);

    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      $total = $this->model
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->count();

      $list = $this->model
        ->with(['business'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      $result = [
        'rows' => $list,
        'total' => $total
      ];

      return json($result);
    }

    return $this->view->fetch();
  }

  // 添加退货
  public function add()
  {
    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');

      // 开启事务
      $this->model->startTrans();
      $this->BackProductModel->startTrans();

      // 查询订单
      $order = $this->OrderModel->where(['code' => $params['ordercode']])->find();

      if (!$order) {
        $this->error(__('订单不存在'));
      }

      // 封装退货单数据
      $BackData = [
        'code' => build_code('BP'),
        'ordercode' => $params['ordercode'],
        'busid' => $order['busid'],
        'remark' => $params['remark']
      ];

      $OrderProduct = $this->OrderProductModel->where(['orderid' => $order['id']])->select();

      if (!$OrderProduct) {
        $this->error(__('订单商品不存在'));
      }

      $BackData['amount'] = $order['amount'];
      $BackData['status'] = 0;
      $BackData['adminid'] = $this->auth->id;

      // 查询地址
      $address = $this->AddressModel->where(['id' => $params['addrid']])->find();

      if (!$address) {
        $this->error(__('请选择联系人以及地址'));
      }

      $BackData['contact'] = $address['consignee'];
      $BackData['phone'] = $address['mobile'];
      $BackData['address'] = $address['address'];
      $BackData['province'] = $address['province'];
      $BackData['city'] = $address['city'];
      $BackData['district'] = $address['district'];

      // 添加退货单
      $backRes = $this->model->validate('common/Depot/Back/Back')->save($BackData);

      if ($backRes === FALSE) {
        $this->error(__($this->model->getError()));
      }

      // 封装退货商品
      $BackProductData = [];

      foreach ($OrderProduct as $item) {
        $BackProductData[] = [
          'backid' => $this->model->id,
          'proid' => $item['proid'],
          'nums' => $item['pronum'],
          'price' => $item['price'],
          'total' => $item['total']
        ];
      }

      // 插入退货商品
      $backProductRes = $this->BackProductModel->validate('common/Depot/Back/BackProduct')->saveAll($BackProductData);

      if ($backProductRes === FALSE) {
        $this->model->rollback();
        $this->error(__($this->BackProductModel->getError()));
      }

      if ($backProductRes === FALSE || $backRes === FALSE) {
        $this->model->rollback();
        $this->BackProductModel->rollback();
        $this->error(__("添加失败"));
      } else {
        $this->model->commit();
        $this->BackProductModel->commit();
        $this->success();
      }
    }
    return $this->view->fetch();
  }
  // 订单信息
  public function orderinfo()
  {
    if ($this->request->isAjax()) {
      $code = $this->request->param('code', '', 'trim');

      $order = $this->OrderModel->where('code', '=', $code)->find();

      if (!$order) {
        $this->error('订单不存在');
        exit;
      }

      $busid = $order['busid'];

      $productList = $this->OrderProductModel->with(['products'])->where(['orderid' => $order['id']])->select();

      if (!$productList) {
        $this->error($this->OrderProductModel->getError());
        exit;
      }

      $addressList = $this->AddressModel->where(['busid' => $busid])->select();

      $order['productList'] = $productList;
      $order['addressList'] = $addressList;

      $this->success('获取成功', '', $order);
      exit;
    }
  }
  // 退货单详情
  public function detail($ids = null)
  {
    $row = $this->model->with(['business'])->find($ids);

    if (!$row) {
      $this->error(__('退货单不存在'));
    }

    $BackProductList = $this->BackProductModel->with(['products'])->where(['backid' => $ids])->select();

    $this->view->assign([
      'row' => $row,
      'BackProductList' => $BackProductList
    ]);

    return $this->view->fetch();
  }
  // 编辑退货
  public function edit($ids = null)
  {
    $row = $this->model->with(['business'])->find($ids);

    if (!$row) {
      $this->error(__('该退货单不存在'));
    }

    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');

      // 开启事务
      $this->model->startTrans();
      $this->BackProductModel->startTrans();

      // 查询订单
      $order = $this->OrderModel->where(['code' => $params['ordercode']])->find();

      if (!$order) {
        $this->error(__('订单不存在'));
      }

      $OrderProduct = $this->OrderProductModel->where(['orderid' => $order['id']])->select();

      if (!$OrderProduct) {
        $this->error(__('订单商品不存在'));
      }

      // 封装退货单数据
      $BackData = [
        'id' => $ids,
        'ordercode' => $params['ordercode'],
        'busid' => $order['busid'],
        'remark' => $params['remark'],
        'amount' => $order['amount'],
        'status' => $row['status'],
        'adminid' => $this->auth->id
      ];

      // 查询地址
      $address = $this->AddressModel->where(['id' => $params['addrid']])->find();

      if (!$address) {
        $this->error(__('请选择联系人以及地址'));
      }

      $BackData['contact'] = $address['consignee'];
      $BackData['phone'] = $address['mobile'];
      $BackData['address'] = $address['address'];
      $BackData['province'] = $address['province'];
      $BackData['city'] = $address['city'];
      $BackData['district'] = $address['district'];

      // 更新数据库
      $backRes = $this->model->isUpdate(true)->save($BackData);

      if ($backRes === false) {
        $this->error(__($this->model->getError()));
      }

      // 默认退货订单状态
      $backProductRes = true;

      // 判断是否订单号有更新
      if ($params['ordercode'] != $row['ordercode']) {
        // 封装退货商品
        $BackProductData = [];

        foreach ($OrderProduct as $item) {
          $BackProductData[] = [
            'backid' => $this->model->id,
            'proid' => $item['proid'],
            'nums' => $item['pronum'],
            'price' => $item['price'],
            'total' => $item['total']
          ];
        }

        $backProductRes = $this->BackProductModel->validate('common/Depot/Back/BackProduct')->saveAll($BackProductData);
      }

      if ($backProductRes === false) {
        $this->model->rollback();
        $this->error(__($this->BackProductModel->getError()));
      }

      if ($backProductRes === false || $backRes === false) {
        $this->model->rollback();
        $this->BackProductModel->rollback();
        $this->error(__("修改失败"));
        exit;
      } else {
        $this->model->commit();
        $this->BackProductModel->commit();
        $this->success();
        exit;
      }
    }

    // 查询地址数据
    $AddressWhere = [
      'consignee' => $row['contact'],
      'mobile' => $row['phone'],
      'address' => $row['address'],
      'province' => $row['province'],
      'city' => $row['city'],
      'district' => $row['district'],
      'busid' => $row['busid']
    ];

    $addrid = model('Business.Address')->where($AddressWhere)->value('id');

    $row['addrid'] = $addrid;

    $BackProductList = $this->BackProductModel->with(['products'])->where(['backid' => $row['id']])->select();

    $AddressData = model('Business.Address')->with(['provinces', 'citys', 'districts'])->where(['busid' => $row['busid']])->select();

    // 封装下拉的数据
    $AddressList = [];

    // 遍历数据
    foreach ($AddressData as $key => $item) {
      $AddressList[$item['id']] = "联系人：{$item['consignee']} 联系方式：{$item['mobile']} 地址：{$item['provinces']['name']}-{$item['citys']['name']}-{$item['districts']['name']} {$item['address']}";
    }

    $this->assignconfig('back', ['BackProductList' => $BackProductList]);

    $data = [
      'row' => $row,
      'AddressList' => $AddressList,
    ];

    return $this->view->fetch('', $data);
  }
  // 审核通过
  public function process()
  {
    if ($this->request->isAjax()) {
      $ids = $this->request->param('ids');

      $row = $this->model->find($ids);

      if (!$row) {
        $this->error(__('退货单不存在'));
      }

      // 封装更新的数据
      $data = [
        'id' => $ids,
        'status' => 1,
        'reviewerid' => $this->auth->id
      ];

      $result = $this->model->isUpdate(true)->save($data);

      if ($result === false) {
        $this->error('审核通过失败');
      } else {
        $this->success();
      }
    }
  }
  // 撤回审核
  public function cancel()
  {
    if ($this->request->isAjax()) {
      $ids = $this->request->param('ids');

      $row = $this->model->find($ids);

      if (!$row) {
        $this->error(__('退货单不存在'));
      }

      // 封装更新的数据
      $data = [
        'id' => $ids,
        'status' => 0,
        'reviewerid' => $this->auth->id
      ];

      $result = $this->model->isUpdate(true)->save($data);

      if ($result === FALSE) {
        $this->error('撤回审核失败');
      } else {
        $this->success();
      }
    }
  }
  // 审核不通过
  public function fail()
  {

    $ids = $this->request->param('ids');

    $row = $this->model->find($ids);

    if (!$row) {
      $this->error(__('退货单不存在'));
    }

    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');

      if (empty($params['reason'])) {
        $this->error('请填写作废理由');
      }

      // 封装更新的数据
      $data = [
        'id' => $ids,
        'status' => '-1',
        'reviewerid' => $this->auth->id,
        'reason' => $params['reason']
      ];

      $result = $this->model->isUpdate(true)->save($data);

      if ($result === FALSE) {
        $this->error('审核不通过失败');
      } else {
        $this->success();
      }

      halt($params);
    }

    return $this->view->fetch();
  }
  // 确认收货
  public function receipt()
  {
    if ($this->request->isAjax()) {
      $ids = $this->request->param('ids');

      $row = $this->model->find($ids);

      if (!$row) {
        $this->error(__('退货单不存在'));
      }

      // 实例化模型
      $BusinessModel = model('Business.Business');

      // 查询订单
      $order = $this->OrderModel->where(['code' => $row['ordercode']])->find();

      if (!$order) {
        $this->error('商品订单不存在');
      }

      $business = $BusinessModel->find($order['busid']);

      if (!$business) {
        $this->error('用户不存在');
      }

      // 开启事务
      $BusinessModel->startTrans();
      $this->model->startTrans();
      $this->OrderModel->startTrans();

      // 封装更新退货单数据
      $data = [
        'id' => $ids,
        'status' => 2
      ];

      $backRes = $this->model->isUpdate(true)->save($data);

      if ($backRes === false) {
        $this->error('确认收货失败');
      }

      // 更新用户的余额
      $BusinessData = [
        'id' => $business['id'],
        'money' => bcadd($order['amount'], $business['money'], 2)
      ];

      $businessRes = $BusinessModel->isUpdate(true)->save($BusinessData);

      if ($businessRes === false) {
        $this->model->rollback();
        $this->error('更新用户余额失败');
      }

      // 更新订单的状态
      $OrderData = [
        'id' => $ids,
        'status' => -4,
      ];

      $orderRes = $this->OrderModel->isUpdate(true)->save($OrderData);

      if ($orderRes === false) {
        $this->model->rollback();
        $BusinessModel->rollback();
        $this->error('更新订单状态失败');
      }

      if ($backRes === false || $businessRes === false || $orderRes === false) {
        $this->model->rollback();
        $BusinessModel->rollback();
        $this->OrderModel->rollback();
        $this->error();
      } else {
        $this->model->commit();
        $BusinessModel->commit();
        $this->OrderModel->commit();
        $this->success();
      }
    }
  }
  // 确认入库
  public function storage()
  {
    if ($this->request->isAjax()) {
      $ids = $this->request->param('ids');

      $row = $this->model->find($ids);

      if (!$row) {
        $this->error(__('退货单不存在'));
      }

      $BackProductList = $this->BackProductModel->where(['backid' => $ids])->select();

      if (!$BackProductList) {
        $this->error(__('退货商品不存在'));
      }

      $StorageModel = model('Depot.storage.Storage');
      $StorageProductModel = model('Depot.storage.Product');

      $StorageModel->startTrans();
      $StorageProductModel->startTrans();
      $this->model->startTrans();

      // 封装入库数据
      $StorageData = [
        'code' => build_code('SU'), // 订单前缀可以自定义\
        'type' => 2,
        'amount' => $row['amount'],
        'status' => 0
      ];

      $storageRes = $StorageModel->validate('common/Depot/storage/Storage.back')->save($StorageData);

      if ($storageRes === false) {
        $this->error($StorageModel->getError());
        exit;
      }

      // 存放封装好的商品数据
      $ProductData = [];

      foreach ($BackProductList as $item) {
        $ProductData[] = [
          'storageid' => $StorageModel->id,
          'proid' => $item['proid'],
          'nums' => $item['nums'],
          'price' => $item['price'],
          'total' => $item['total'],
        ];
      }

      // 验证数据
      $productRes = $StorageProductModel->validate('common/Depot/storage/Product')->saveAll($ProductData);

      if ($productRes === false) {
        $StorageModel->rollback();
        $this->error($StorageProductModel->getError());
      }

      // 更新退货单的数据
      $BackData = [
        'id' => $row['id'],
        'status' => 3,
        'stromanid' => $this->auth->id,
        'storageid' => $StorageModel->id
      ];

      $backRes = $this->model->isUpdate(true)->save($BackData);

      if ($backRes === false) {
        $StorageModel->rollback();
        $StorageProductModel->rollback();
        $this->error($this->model->getError());
      }

      // 大判断
      if ($productRes === false || $storageRes === false || $backRes === false) {
        $StorageModel->rollback();
        $StorageProductModel->rollback();
        $this->model->rollback();
        $this->error(__('入库失败'));
      } else {
        $StorageModel->commit();
        $StorageProductModel->commit();
        $this->model->commit();
        $this->success();
      }
    }
  }
  // 软删除
  public function del($ids = null)
  {
    if ($this->request->isAjax()) {
      $row = $this->model->where(['id' => ['in', $ids]])->select();

      if (empty($row)) {
        $this->error(__('请选择需要删除退货单'));
      }

      $result = $this->model->destroy($ids);

      if ($result === FALSE) {
        $this->error(__('删除退货单失败'));
      } else {
        $this->success();
      }
    }
  }
  // 回收站
  public function recyclebin()
  {
    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      // 过滤请求参数中的html标签和取消两边你空白
      $this->request->filter(['strip_tags', 'trim']);
      // 获取查询参数
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();


      $total = $this->model
        ->onlyTrashed()
        ->where($where)
        ->count();

      $list = $this->model
        ->onlyTrashed()
        ->with(['business'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // var_dump($this->model->getLastSql());
      // exit;

      $result = [
        'rows' => $list,
        'total' => $total,
      ];

      return json($result);
    }

    return $this->view->fetch();
  }
  // 还原
  public function restore($ids = null)
  {
    $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

    if (!$row) {
      $this->error(__('请选择需要还原记录'));
    }

    $result = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->update(['deletetime' => null]);

    if ($result != true) {
      $this->error(__('还原失败'));
    } else {
      $this->success();
    }
  }
  // 销毁
  public function destroy($ids = null)
  {
    if ($this->request->isAjax()) {
      $ids = explode(',', $ids);
      $ids = empty($ids) ? [] : $ids;

      $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

      if (empty($row)) {
        $this->error(__('请选择需要销毁的记录'));
      }

      $this->model->startTrans();
      $this->BackProductModel->startTrans();

      $BackProduct = $this->BackProductModel->where(['backid' => ['in', $ids]])->column('id');

      $backRes = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->delete();

      if ($backRes === false) {
        $this->error($this->model->getError());
        exit;
      }

      $productRes = $this->BackProductModel->where(['id' => ['in', $BackProduct]])->delete();

      if ($productRes === false) {
        $this->model->rollback();
        $this->error($this->BackProductModel->getError());
        exit;
      }

      // 删除退货图集
      foreach ($row as $item) {
        if (!empty($item['thumbs'])) {
          $thumbs = explode(',', $item['thumbs']);
          foreach ($thumbs as $val) {
            @is_file('.' . $val) && @unlink('.' . $val);
          }
        }
      }

      if ($backRes === false || $productRes === false) {
        $this->model->rollback();
        $this->BackProductModel->rollback();
        $this->error('销毁失败');
        exit;
      } else {
        $this->BackProductModel->commit();
        $this->model->commit();
        $this->success('销毁成功');
        exit;
      }
    }
  }
}
